package net.lovesrc.allin.biz.dida;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhouzhou.fastjava.BizException;
import com.zhouzhou.fastjava.http.Requests;
import net.lovesrc.allin.biz.BaseService;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * User: liuzheqiang
 * Date: 2018/4/2
 * Time: 16:52
 */
@Service
public class ListingService extends BaseService {

    public static Map<String, Object> HEADERS = Maps.newHashMap();

    public static String PHP_SESSION = "ak9vj15t51ke8ejkm8r12dpu03";

    public static String TOKEN = "4c9720b8-d23a-4c18-866d-7d3165d88740";

    public static String DDC_INFO = "zkK0fyZ7RrsC+SKG7g3mtiru+mqhlmanharNjGh53y4PwPSJltJHf00GD+BMhAHdvLLqQq8MPxr6kjel+Buxd6Cpu3IsuZTPjN5bM7KI99+Ki3/ada/uuXzjCOZPsPiskQDcgRis2ePJ6eL50LC4ZEgY2C8kSmAcisssw0eKh89JBbIMky3YFb0LLN6KEaCBmc4jaNywdvTZp/EPkX8H77HaMVlxnG7eVTrMKlQ/i5ZAmMSCMyS50uKeoANwPaPXbo1Mh/tHHfqulAlILGvaLXcL1FbU1dSSNTJl8BcMJvEbxC8hBRH++K2zsLTLcSSvF/Tr+IvI5E3Sk/Y7Za5ZbdZdv7+b7OmkpwYtyRbZfQ6b76oJ6le4grGWAaiPmZYQdmM2fXixNuBLD5fURfUxA5xgnO2yvEsj3vC/gOxTjhqQwxsx7/WpzlafTJpeEZiEyh02s1/Bg1kbFAbOa5U6/jaOTIoYfofDCdD+FZJJoSKY7Qr/AjGMSeCiqRZoOvoc04Ht7fHO9ypIXtjD9hLbRuKXYtOWewioY7TQPFak6qgyOD0FTRqbGEwUsjQ5aAQS2K8WrS4nnZPh51dswiWDgmWUMTNshUpD/pLsCO9olLfNAYsqqI5K2sCY5VfA8SCNBW+Fy63clmUS9KGc1Pzv1FbdDI+l00n9rOI3qNQ72IuhDpJv3I6TBxLPAOX94HTcQtIOa2pPfRihs/yQEIVDYuGyAW18MaZhP0WQTMN7Z2vb2aYhJfU/1zA8/0HZQrnJpMSHfEEiv6tXTFIo3MMzRxF3+CNR5av8X4BQrOHenUCt2aOK5xn6AX2iuYqi+UgV5EumLjUm5zRbKOe8FwrQ+ZJ1c+GdRufnrcM+zg+90OgCnJk2wylSi2P37veu8dC46NAMk2pZyQI=";

    public static String VERSION = "8.3.6";

    static {
        HEADERS.put("Content-Type", "application/x-www-form-urlencoded");
        HEADERS.put("Cookie", "PHPSESSID=" + PHP_SESSION);
        HEADERS.put("Connection", "keep-alive");
        HEADERS.put("Accept", "*/*");
        HEADERS.put("User-Agent", "DidaPinche/8.3.6 dc(eyJsYXQiOjMxLjEyNjkzMCwibG9uIjoxMjEuNjA0MDgwfQ==) (iOS 12.3.1;iPhone8,2) [[App]] Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148");
        HEADERS.put("Accept-Language", "en-CN;q=1, zh-Hans-CN;q=0.9");
        HEADERS.put("Accept-Encoding", "gzip, deflate");
        HEADERS.put("ddcinfo", DDC_INFO);
    }

    /***
     * 根据 出发地&目的地，搜索
     */
    public List<Listing> getBookingRideListV2(LocalTime time, Double sLat, Double sLng, Double eLat, Double eLng) {
        return doGetBookingRideListV2(1, time, sLat, sLng, eLat, eLng);
    }

    private List<Listing> doGetBookingRideListV2(int page, LocalTime time, Double sLat, Double sLng, Double eLat, Double eLng) {

        logger.info("正在获取第{}页的数据, time: {}", page, time);
        Map<String, Object> params = Maps.newHashMap();
        params.put("actid", "dida_app");
        params.put("mobiletype", "1");
        params.put("page", String.valueOf(page));
        params.put("page_size", "20");
        params.put("plan_start_time", time.format(DateTimeFormatter.ofPattern("HHmm")));
        params.put("start_lat", sLat.toString());
        params.put("start_lon", sLng.toString());
        params.put("end_lat", eLat.toString());
        params.put("end_lon", eLng.toString());
        params.put("token", TOKEN);
        params.put("user_cid", "290984cd-80a4-4463-a547-8864dfb0c346");
        //params.put("usual_route_id", "8744242");
        params.put("version", VERSION);

        SignUtils.signParams(params);

        JSONObject resJson = Requests.post("http://bapi-slb.didapinche.com/V3/BookingDriver/getBookingRideListV2")
                .headers(ListingService.HEADERS)
                .params(params)
                .printResText(false)
                .executeUtilReturn200()
                .asJson();
        int code = resJson.getIntValue("code");
        if (code != 0) {
            logger.error("error response, text: {}", resJson);
            throw BizException.messageOf("请求ERROR");
        }
        List<JSONObject> jsonListings = JSON.parseArray(resJson.getJSONArray("list").toJSONString(), JSONObject.class);
        if (jsonListings.isEmpty()) {
            return Lists.newArrayList();
        }
        return jsonListings.stream()
                .map(r -> {
                    Listing listing = r.toJavaObject(Listing.class);
                    listing.setOrigin(r);
                    listing.setOriginText(r.toJSONString());
                    return listing;
                })
                .collect(Collectors.toList());
    }


    public JSONObject getRideOrderDetail(Long rideId) {

        Map<String, Object> params = Maps.newHashMap();
        params.put("actid", "dida_app");
        params.put("mobiletype", "1");
        params.put("ride_id", String.valueOf(rideId));
        params.put("token", TOKEN);
        params.put("user_cid", "290984cd-80a4-4463-a547-8864dfb0c346");
        params.put("version", VERSION);

        SignUtils.signParams(params);

        return Requests.post("http://bapi-slb.didapinche.com/V3/BookingDriver/getRideOrderDetail")
                .headers(ListingService.HEADERS)
                .params(params)
                .printResText(false)
                .executeUtilReturn200()
                .asJson();
    }

}
